package com.zhentao.config;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.zhentao.pojo.Product;
import com.zhentao.service.ProductService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Excel导入工具类，用于将Excel数据导入到Product表
 */
@Component
public class ExcelImportService {

    private final ProductService productService; // 需要注入ProductService

    public ExcelImportService(ProductService productService) {
        this.productService = productService;
    }

    /**
     * 导入Excel数据
     * @param inputStream Excel文件输入流
     */
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(InputStream inputStream) {
        // 创建读取监听器
        ProductExcelListener listener = new ProductExcelListener(productService);

        // 构建Excel读取器
        ExcelReaderBuilder readerBuilder = EasyExcel.read(inputStream, Product.class, listener);

        // 构建工作表读取器并读取数据
        ExcelReaderSheetBuilder sheetBuilder = readerBuilder.sheet();
        sheetBuilder.doRead();
    }

    /**
     * Excel读取监听器
     */
    public static class ProductExcelListener extends AnalysisEventListener<Product> {

        private static final int BATCH_SIZE = 500;
        private final List<Product> products = new ArrayList<>();
        private final ProductService productService;

        public ProductExcelListener(ProductService productService) {
            this.productService = productService;
        }

        /**
         * 每读取一行数据时调用
         */
        @Override
        public void invoke(Product product, AnalysisContext context) {
            // 数据校验
            validateProduct(product);
            products.add(product);

            // 达到批处理数量时，批量插入数据
            if (products.size() >= BATCH_SIZE) {
                saveData();
                products.clear();
            }
        }

        /**
         * 读取完成后调用
         */
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            // 处理剩余数据
            if (!products.isEmpty()) {
                saveData();
            }
        }

        /**
         * 保存数据到数据库
         */
        private void saveData() {
            productService.saveBatch(products);
        }

        /**
         * 数据校验
         */
        private void validateProduct(Product product) {
            // 校验商品名称不能为空
            if (product.getName() == null || product.getName().trim().isEmpty()) {
                throw new IllegalArgumentException("商品名称不能为空");
            }
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            product.setIsDeleted(1);
            // 校验价格不能为负数
            if (product.getPrice() != null && product.getPrice() < 0) {
                throw new IllegalArgumentException("商品价格不能为负数");
            }

            // 校验库存不能为负数
            if (product.getStock() != null && product.getStock() < 0) {
                throw new IllegalArgumentException("库存数量不能为负数");
            }

            // 校验状态值
            if (product.getStatus() != null && (product.getStatus() != 0 && product.getStatus() != 1)) {
                throw new IllegalArgumentException("商品状态值必须为0或1");
            }
        }
    }
}
